package com.utils;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 

import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
 
/**
 * APP登录Token的生成和解析
 * 
 */
public class JwtToken {
 
	/** token秘钥，请勿泄露，请勿随便修改 backups:JKKLJOoasdlfj */
	public static final String SECRET = "JBFAFB^^&%^&*&68t78ydasdgby,.p;Asguigf87tasyfvgys";
	/** token 过期时间: 10天 */
	public static final int calendarField = Calendar.DATE;
	public static final int calendarInterval = 365;
 
	/**
	 * JWT生成Token.<br/>
	 * 
	 * JWT构成: header, payload, signature
	 * 
	 * @param user_id
	 *            登录成功后用户user_id, 参数user_id不可传空
	 */
	public static String createToken(Long user_id) throws Exception {
		Date iatDate = new Date();
		// expire time
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(calendarField, calendarInterval);
		Date expiresDate = nowTime.getTime();
 
		// header Map
		Map<String, Object> map = new HashMap<>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");
 
		// build token
		// param backups {iss:Service, aud:APP}
		String token = JWT.create().withHeader(map) // header
				.withClaim("iss", "Service") // payload
				.withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id.toString())
				.withIssuedAt(iatDate) // sign time
				.withExpiresAt(expiresDate) // expire time
				.sign(Algorithm.HMAC256(SECRET)); // signature
 
		return token;
	}
 
	/**
	 * 解密Token
	 * 
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Claim> verifyToken(String token) {
		DecodedJWT jwt = null;
		try {
			JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
			jwt = verifier.verify(token);
		} catch (Exception e) {
			// e.printStackTrace();
			// token 校验失败, 抛出Token验证非法异常
		}
		return jwt.getClaims();
	}
 
	/**
	 * 根据Token获取user_id
	 * 
	 * @param token
	 * @return user_id
	 * @throws Exception 
	 */
	public static Long getAppUID(String token) throws Exception {
		Map<String, Claim> claims = verifyToken(token);
		Claim user_id_claim = claims.get("user_id");
		if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
			// token 校验失败, 抛出Token验证非法异常
			throw new Exception("Token 异常,请重新登录");
		}
		return Long.valueOf(user_id_claim.asString());
	}
	
	
	public static void main(String[] args) {
		try {
			
			// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODg2NjY1OTUsImF1ZCI6IkFQUCIsImlzcyI6IlNlcnZpY2UiLCJ1c2VyX2lkIjoiMiIsImlhdCI6MTU1NzEzMDU5NX0.3GDmynzDQU3tgBNST070qq_RFUsjs_sKohQ5sr_eGlc
			// 150 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTAyMTg4MzUsImF1ZCI6IkFQUCIsImlzcyI6IlNlcnZpY2UiLCJ1c2VyX2lkIjoiMTUwIiwiaWF0IjoxNTU4NjgyODM1fQ.Ma-LRYnjLAx5NayOITyKxn_6s6042FlYX_rRx7l60c8
			// 140901   eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTE2ODk1MDQsImF1ZCI6IkFQUCIsImlzcyI6IlNlcnZpY2UiLCJ1c2VyX2lkIjoiMTQwOTAxIiwiaWF0IjoxNTYwMTUzNTA0fQ.QwTi5TgBsk9jLsUuI3DXXbdAHMPIqn48nlyGTHHnsVM
			
			//54854  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTM1ODg4MTUsImF1ZCI6IkFQUCIsImlzcyI6IlNlcnZpY2UiLCJ1c2VyX2lkIjoiNTQ4NTQiLCJpYXQiOjE1NjIwNTI4MTV9.fp1crzymZqgXVBzCAxd3dhTJgxT8hb2C4ZZiZUmsk-0
			System.out.println(createToken(140901L));
			System.out.println(JwtToken.getAppUID("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiMTAwODAwOCIsImlzcyI6IlNlcnZpY2UiLCJleHAiOjE2MjY0MTIxNjIsImlhdCI6MTU5NDg3NjE2Mn0.9IC1mEnwqeov_DhgaC8BdCXAqCAcsOzljOPvz1zedxM"));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
